package com.fwx.jdbc;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @author : fengwenxiang
 * @date : 2022/5/12 22:44
 * @description：原生JDBC工具类的使用
 */
public class JdbcUtil {
    //静态变量是实例所共享的,存放在方法区，即使后续创建多个实例，也只会使用一个静态变量的值
    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    //静态代码块初始化--类加载阶段会直接执行代码块内容,只执行一次
    static{
        try{
            //读取properties配置文件的数据
            InputStream resourceAsStream = JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
            Properties properties = new Properties();
            properties.load(resourceAsStream);
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            Class.forName(driver);//注册驱动
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public static Connection getConn() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, username, password);
        }catch (Exception e){
            e.printStackTrace();
        }
        return connection;
    }
    //关闭资源
    public static void close(Connection conn, PreparedStatement ps){
        if(ps != null){
            try{
                ps.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        if(conn != null){
            try{
                conn.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }
    //重载形式关闭资源，查询的时候使用
    public static void close(Connection conn, PreparedStatement ps, ResultSet rs){
        if(rs != null){
            try{
                rs.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        close(conn,ps);
    }
}
